<?php

namespace Beerus\Modules\DesignerAuth\Controllers;

use App\Http\Controllers\Controller;
use Doraemon\cache\Queue;
use Doraemon\cache\User as CacheUser;
use Doraemon\model\Designer;
use Doraemon\model\Designer\DesignerAuditLog;
use Doraemon\model\Designer\DesignerOpLog;
use Doraemon\model\DesignerAuth;
use Doraemon\model\DesignerAuthExtend;
use Doraemon\model\DesignerCompanyCheck;
use Doraemon\model\Member;
use Doraemon\service\Designer\AuthService;
use Doraemon\service\Designer\DesignerDingTalkAlert;
use Doraemon\service\DingTalkAlert;
use Doraemon\service\search\DesignerSearch;
use Doraemon\service\User;
use Doraemon\service\WechatAlert;
use Doraemon\tools\HhzEnv;
use Doraemon\tools\HhzNiceLivingUrl;
use Doraemon\tools\Hhzurl;
use Encore\Admin\Facades\Admin;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;

class InfoAuditController extends Controller
{
	public function __construct()
	{
		parent::__construct();
		Admin::script('$(".pjax-container").attr("id","pjax-container");');
	}

	// 资料审核弹框页面
	public function rejectLayer($uid)
	{
		$reject_reasons = [
			'',
			'手持身份证照片不符合规范',
			'身份证正面照片不符合规范',
			'身份证反面照片不符合规范',
			'申请公函与申请身份不对应',
			'申请公函没有填写时间',
			'营业执照照片不符合规范（须是原件）',
			'符合免费「青年计划」政策',
		];

		$auth_info = DesignerAuth::getByUId($uid);

		return view('DesignerAuth::audit.info_reject', [
			'uid' => $uid,
			'reject_reasons' => $reject_reasons,
			'remark' => $auth_info['remark'],
			'reason' => $auth_info['reason']
		]);
	}

	// 资料审核不通过
	public function reject(Request $request)
	{
		$params = $request->all();

		$reason = $params['reason'];
		if (empty($reason)) {
			return response()->json(['msg' => '操作失败，请选择审核不通过的原因', 'code' => 0]);
		}

		$uid = $params['uid'];

		$auth_info = DesignerAuth::getByUId($uid);

		$audit_log = DesignerAuditLog::getByCondition([
			'AND' => [
				'uid' => $uid,
				'audit_type' => DesignerAuditLog::AUDIT_TYPE_INFORMATION,
			],
			'ORDER' => ['add_time' => 'DESC'],
		]);

		// 检查是否是认证期内改身份
		if ($auth_info['auth_status'] == DesignerAuth::STATUS_AUTH_COMPLETE && $audit_log['designer_type'] != $auth_info['designer_type']
			&& HhzEnv::isProduction() && !in_array(Admin::user()->username, AuthService::OPERATOR)) {
			return response()->json(['msg' => '抱歉，认证期内改身份, 你没有权限操作，请联系运营', 'code' => 0]);
		}

		DesignerAuditLog::updateInfo($audit_log['id'], [
			'audit_status' => DesignerAuditLog::AUDIT_STATUS_FAIL,
			'reason' => $reason,
			'edit_time' => time(),
			'admin_id' => Admin::user()->id,
		]);

		$res = DesignerAuth::updateInfo($params['uid'], [
			'reason' => $reason,
			'remark' => $params['remark'],
			'identity_info_audit_status' => DesignerAuth::STATUS_AUDIT_FAIL,
			'admin_id' => Admin::user()->id,
			'admin_name' => Admin::user()->username,
			'operate_time' => time(),
		]);

		if (empty($res)) {
			return response()->json(['msg' => '操作失败，请稍后重试', 'code' => 0]);
		} else {
			// 记录运营审核不通过的日志
			$admin_name = Admin::user()->username;
			$id = DesignerOpLog::create([
				'uid' => $uid,
				'op' => DesignerOpLog::INFO_AUDIT_FAIL,
				'reason' => $reason,
				'op_time' => date('Y-m-d H:i:s'),
				'admin_id' => Admin::user()->id,
				'admin_name' => $admin_name
			]);

			if ($id) {
				$msg = implode("\n", [
					"操作：资料审核不通过",
					"设计师uid：{$uid}",
					"不通过的原因：{$reason}",
					"操作人：{$admin_name}\n",
				]);
                DesignerDingTalkAlert::sendBeerusDesignerAuthAuditMsg2Operator($uid, $msg);

				// 发送下行告知用户审核未通过
				Queue::insertQueue('queue/Sysmsg/Send', [
					'msgCode' => 0,
					'to_uid' => $uid,
					'msgParams' => [
						'from_uid' => User::DEFAULT_HAOHAOZHU_UID,
						'title' => '',
						'detail' => '很遗憾，你的申请因为「'. $reason .'」没有通过审核，请修改相关内容，重新上传。'
					]
				], Queue::QUEUE_DORAEMON);
			}

			return response()->json(['msg' => '操作成功', 'code' => 1]);
		}
	}

	// 资料审核通过
	public function pass($uid)
	{
		// 检查当前用户的状态是否可以继续进行"拒绝操作"
		$auth_info = DesignerAuth::getByUid($uid);
		$audit_log = DesignerAuditLog::getByCondition([
			'AND' => [
				'uid' => $uid,
				'audit_type' => DesignerAuditLog::AUDIT_TYPE_INFORMATION,
			],
			'ORDER' => ['add_time' => 'DESC'],
		]);

		$message = '哈喽，你的认证资料已经通过审核';

		if ($auth_info['house_article_audit_status'] == DesignerAuth::STATUS_AUDIT_PASS &&
			$auth_info['designer_type'] != DesignerAuth::DESIGNER_TYPE_COMPANY_BYPASS) {
			$message = '哈喽，你的作品和认证资料已经通过审核，电脑登录好好住官网www.haohaozhu.com完成支付吧！';
		}

		// 检查是否是认证期内改身份
		if ($auth_info['auth_status'] == DesignerAuth::STATUS_AUTH_COMPLETE && $audit_log['designer_type'] != $auth_info['designer_type']
		 && HhzEnv::isProduction() && !in_array(Admin::user()->username, AuthService::OPERATOR)) {
			$error = new MessageBag([
				'title' => '抱歉，认证期内改身份，你没有权限操作，请联系运营'
			]);
			return back()->with(compact('error'));
		}

		$auth_info['designer_type'] = (int)$audit_log['designer_type'];

		if ($auth_info['designer_type'] == DesignerAuth::DESIGNER_TYPE_COMPANY_BYPASS) {
			Queue::insertQueue('queue/Sysmsg/Send', [
				'msgCode' => 602,
				'to_uid' => $uid,
			], Queue::QUEUE_DORAEMON);

			$latest = DesignerCompanyCheck::getLastMemberInfo($uid);

			$member_info = Member::getOne($uid);

			$url = Hhzurl::getDomain(). '/designer/organization-account-management/get-application-status?id='. $latest['id'];
			Queue::insertQueue('queue/Sysmsg/Send', [
				'msgCode' => 603,
				'to_uid' => $latest['org_uid'],
				'msgParams' => [
					'designer_name' => $member_info['nick'],
					'link' => HhzNiceLivingUrl::getNormalH5Link($url),
				]
			], Queue::QUEUE_DORAEMON);

			DesignerCompanyCheck::update([
				'check_status' => DesignerCompanyCheck::CHECK_STATUS_DEFAULT,
			], [
				'id' => $latest['id']
			]);
		} else {
			Queue::insertQueue('queue/Sysmsg/Send', [
				'msgCode' => 0,
				'to_uid' => $uid,
				'msgParams' => [
					'from_uid' => User::DEFAULT_HAOHAOZHU_UID,
					'title' => '',
					'detail' => $message
				]
			], Queue::QUEUE_DORAEMON);
		}

		// 使用新资料覆盖老资料
		$new_data = json_decode($audit_log['new_data'], true);
		unset(
			$new_data['auth_info']['house_article_audit_status'],
			$new_data['auth_info']['auth_status'],
			$new_data['auth_info']['auth_time'],
			$new_data['auth_info']['expire_time'],
            $new_data['auth_info']['phone'],
		);
		$new_data['auth_info']['identity_info_audit_status'] = DesignerAuth::STATUS_AUDIT_PASS;
		$new_data['auth_info']['operate_time'] = time();
		$new_data['auth_info']['designer_type'] = empty($audit_log['designer_type']) ? $auth_info['designer_type'] : $audit_log['designer_type'];
		unset($new_data['auth_info']['is_pay']);

		$auth_data = $new_data['auth_info'];
		$auth_data['admin_id'] = Admin::user()->id;
		$auth_data['admin_name'] = Admin::user()->username;
		$auth_data['operate_time'] = time();
		DesignerAuth::updateInfo($uid, $auth_data);
		DesignerAuthExtend::updateInfo($uid, $new_data['extend_info']);

		if ((int)$auth_info['auth_status'] === DesignerAuth::STATUS_AUTH_COMPLETE) {
			Designer::updateDesigner($uid, [
				'designer_type' => $new_data['auth_info']['designer_type']
			]);
			DesignerSearch::updateDesignerByUid($uid);
			CacheUser::deleteUserInfo($uid);
		}

		// 更新审核记录为已通过
		DesignerAuditLog::updateInfo($audit_log['id'], [
			'audit_status' => DesignerAuditLog::AUDIT_STATUS_PASS,
			'edit_time' => time(),
			'admin_id' => Admin::user()->id,
		]);

		// 记录运营操作日志
		$admin_name = Admin::user()->username;
		$id = DesignerOpLog::create([
			'uid' => $uid,
			'reason' => '资料通过审核',
			'op' => DesignerOpLog::INFO_AUDIT_PASS,
			'op_time' => date('Y-m-d H:i:s'),
			'admin_id' => Admin::user()->id,
			'admin_name' => $admin_name
		]);

		if ($id) {
			$msg = implode("\n", [
				"操作：资料审核通过",
				"设计师uid：{$uid}",
				"操作人：{$admin_name}\n",
			]);
            DesignerDingTalkAlert::sendBeerusDesignerAuthAuditMsg2Operator($uid, $msg);
		}

		$success = new MessageBag([
			'title' => '操作成功'
		]);
		return back()->with(compact('success'));
	}
}
